<template>
  <div class="login-box">
    <div class="login-bg"></div>
    <div class="login-form-wrap">
      <img class="tianchu-logo" src="@/assets/images/login/logo.png" alt="" />
      <div class="login-form-left">
        <div class="title">一粒米收银系统登录</div>
        <img
          src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
          class="avater-img"
          alt=""
        />
        <div class="login-form">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="0" status-icon>
            <div class="row">
              <el-form-item prop="phone">
                <el-input
                  v-model.trim="form.phone"
                  placeholder="请输入手机号"
                  clearable
                  maxlength="11"
                  inputmode="numeric"
                  type="tel"
                  @input="handlePhoneInput"
                  style="flex: 1"
                >
                  <template #prefix>
                    <el-icon class="row-icon"><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <div class="row">
              <el-form-item prop="password">
                <el-input
                  v-model.trim="form.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                  style="flex: 1"
                >
                  <template #prefix>
                    <el-icon class="row-icon"><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <el-button
              class="login-btn"
              type="primary"
              :loading="loading"
              :disabled="buttonDisabled"
              @click.prevent="onLogin"
              >登录</el-button
            >
            <div class="checked-desc">
              <el-form-item prop="isAgree">
                <el-checkbox v-model="form.isAgree">
                  接受并同意<a class="link">《用户协议》</a> 和 <a class="link">《隐私协议》</a>
                </el-checkbox>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="login-form-right">
        <div class="image"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { LocalStorage } from '@/utils/storage'
import { passportLogin } from '@/api/user'
import DataSyncService from '@/services/dataSyncService'
import { syncCXTData } from '@/webSocket/cxt/operations'
import { User, Lock } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
const router = useRouter()
const userStore = useUserStore()
const formRef = ref<FormInstance>()
const form = reactive({ phone: '', password: '', isAgree: false })
const buttonDisabled = ref(false)
const loading = ref(false)

function handlePhoneInput(val: string) {
  form.phone = (val || '').replace(/\D/g, '').slice(0, 11)
}
const validateAgree = (_rule: any, value: boolean, callback: (error?: Error) => void) => {
  if (value) callback()
  else callback(new Error('请先勾选协议'))
}

const rules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  isAgree: [{ validator: validateAgree, trigger: 'change' }]
})

// 数据同步函数
async function performDataSync() {
  try {
    // 非 Electron 环境下不执行数据同步
    const isElectron =
      (typeof process !== 'undefined' && (process as any)?.versions?.electron) ||
      (typeof navigator !== 'undefined' && /Electron/i.test(navigator.userAgent))
    if (!isElectron) {
      console.log('非 Electron 环境，跳过数据同步。')
      return
    }
    console.log('开始执行数据同步...')

    // 使用数据同步服务
    const results = await DataSyncService.startSync((step, total, status) => {
      console.log(`同步进度: ${step}/${total} - ${status}`)
    })

    // 统计同步结果
    const successCount = results.filter(r => r.success).length
    const failCount = results.filter(r => !r.success).length

    console.log(`SQLite 数据同步完成: 成功 ${successCount} 个表, 失败 ${failCount} 个表`)
    ElMessage.success(`SQLite 数据同步完成: 成功 ${successCount} 个表, 失败 ${failCount} 个表`)

    if (failCount > 0) {
      console.warn('部分表同步失败，但不影响登录流程')
    }

    // 执行 CXT 数据同步
    try {
      console.log('开始执行 CXT 数据同步...')
      await syncCXTData()
      console.log('CXT 数据同步完成')
    } catch (error) {
      console.warn('CXT 数据同步失败，但不影响登录流程:', error)
    }
  } catch (error) {
    console.error('数据同步过程出错:', error)
    // 即使同步失败也不影响登录流程
  }
}

async function onLogin() {
  if (!formRef.value) return
  const isValid = await formRef.value.validate().catch(() => false)
  if (!isValid) return
  if (buttonDisabled.value || loading.value) return
  buttonDisabled.value = true
  loading.value = true
  try {
    // 调用登录接口，保存 token，再统一拉一次用户数据
    const res: any = await passportLogin({ username: form.phone, password: form.password })
    buttonDisabled.value = false
    if (res?.status === 200) {
      const token = res?.data?.token || ''
      const userId = res?.data?.userId || ''
      LocalStorage.set('userId', userId)
      LocalStorage.set('token', token)
      userStore.setToken(token)
      await userStore.initLoadUserProfile()

      // 登录成功后执行数据同步
      await performDataSync()

      // 同步完成后跳转到首页
      router.replace('/home')
    }
  } finally {
    buttonDisabled.value = false
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.login-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  //   background: #f5f7fa;
}
.login-bg {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  width: 977px;
  z-index: 1;
  background: url('@/assets/images/login/login-bg.png');
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form-wrap {
  //   position: absolute;
  //   left: 50%;
  //   top: 130px;
  position: relative;
  //   transform: translateX(-50%);
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 1560px;
  height: 820px;
  background: #ffffff;
  box-shadow: 6px 27px 33px 0px rgba(38, 2, 0, 0.18);
  box-sizing: border-box;

  .tianchu-logo {
    position: absolute;
    left: 46px;
    top: 46px;
    z-index: 3;
    width: 126px;
    height: 70px;
  }

  .login-form-left {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 793px;
    height: 820px;
    padding-top: 60px;
    box-sizing: border-box;

    .title {
      font-size: 32px;
      font-weight: 700;
      text-align: center;
      color: #333333;
    }
    .avater-img {
      width: 88px;
      height: 88px;
      border-radius: 50%;
      margin-top: 40px;
      flex-shrink: 0;
    }

    .login-form {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 525px;
      height: 454px;
      background-image: url('@/assets/images/login/form-bg.png');
      background-size: 100% 100%;
      box-sizing: border-box;
      padding-top: 98px;

      .row {
        width: 395px;
        display: flex;
        align-items: center;
        position: relative;
        padding-bottom: 11px;
        border-bottom: 1px solid #d2d2d2;
      }
      .row + .row {
        margin-top: 50px;
      }

      /* 去除 el-input 外边框，仅保留下边框 */
      :deep(.el-input__wrapper) {
        box-shadow: none !important;
        background: transparent;
        padding-left: 0;
      }
      :deep(.el-input__inner) {
        padding-left: 0;
      }
      :deep(.el-input) {
        width: 300px;
      }
      :deep(.el-form-item) {
        margin-bottom: 0;
        width: 100%;
      }
      :deep(.el-form-item__content) {
        width: 100%;
      }
      :deep(.el-form-item__error) {
        position: absolute;
        top: 100%;
        left: 0;
        margin-top: 12px;
        line-height: 1;
      }
      :deep(.el-form-item.is-error .el-input__wrapper) {
        box-shadow: none !important;
      }
      :deep(.el-checkbox) {
        height: 0px !important;
      }
      .row-icon {
        margin-right: 10px;
        color: #999;
      }

      .login-btn {
        width: 404px;
        height: 52px;
        margin-top: 70px;
        border-radius: 12px;
      }

      /* Align checkbox line with input rows */
      .checked-desc {
        width: 395px;
        align-self: center;
        margin-top: 30px;
      }
      .link {
        color: #23a0d7;
        cursor: pointer;
      }
    }
  }

  .login-form-right .image {
    flex-shrink: 0;
    width: 767px;
    height: 860px;
    background: url('@/assets/images/login/login-form-img.png');
    background-size: cover;
  }
}
</style>
